<template>
  <div class="container">
    <mars3d-viewer ref="location-viewer" url="/api/location/config/map/load" @mapLoaded="mapLoaded"></mars3d-viewer>
    <el-card class="box-card" style="width: 15%;height: 400px; position: absolute; top: 50px; left: 10px; opacity: 80%">
      <div slot="header" class="clearfix">
        <span>区域建筑</span>
        <!--        <el-button style="float: right; padding: 3px 0" type="text">收起</el-button>-->
      </div>
      <div class="text item" style="overflow-y: scroll">
        <el-tree
          class="filter-tree"
          show-checkbox
          :data="buildingData"
          :props="{children: 'children', label: 'name'}"
          default-expand-all
          @check-change="showBuilding"
          ref="tree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>&nbsp;
            <span  style="float: right;color: #1E90FF">
              <i class="el-icon-crop" v-if="data.area && data.area.length > 0" title="已勾画区域"></i>
              <i class="el-icon-office-building" v-if="data.modelConfig && data.modelConfig != '{}'" title="已配置建筑"></i>
            </span>
          </span>
        </el-tree>
      </div>
    </el-card>
    <el-card class="box-card" style="width: 15%;height: 400px; position: absolute; top: 460px; left: 10px; opacity: 80%">
      <div slot="header" class="clearfix">
        <span>定位统计</span>
      </div>
      <div class="text item">
        <div ref="chart" style="width: 100%;height:200px">

        </div>
      </div>
    </el-card>
    <location-engine ref="location-engine" v-show="false" @initScene="initScene" @location="location"></location-engine>
  </div>
</template>
<script>

import Mars3dViewer from "@/components/mars3d-earth/map/show";
import LocationEngine from "./engine"
import {buildingAreaListAPI} from "@/api/location/buildingarea/buildingarea";
import tableMixins from "@/mixins/table";

export default {
  mixins: [tableMixins],

  name: 'locationViewer',

  components: {Mars3dViewer, LocationEngine},

  data() {
    return {
      allData: {},//全部定位数据
      allDepInfo: {},//全部统计信息
      baseHeight: 0,//地图基准高度
      buildingData: [],//建筑参数信息
      buildingShowList: {},//显示的建筑清单
      tilesetClipList: {},//模型开挖列表
    };
  },

  created() {

  },

  methods: {
    //地图加载完成回调
    mapLoaded(map, options){
      //this.$refs["location-engine"].getConnection("ws://" + document.location.host + "/api/location/websocket/location")
      this.$refs["location-engine"].getConnection("ws://192.168.1.8:18012/websocket/location")
      this.graphicLayer = new mars3d.layer.GraphicLayer({
        popup: (e)=>{
          return mars3d.Util.getTemplateHtml({
            title: e.graphic.attr.thing.name,
            template: "all",
            attr: {
              "名称": e.graphic.attr.thing.name,
              "类型": e.graphic.attr.thing.type.value,
              "楼层": (e.graphic.attr.position.floor && e.graphic.attr.position.floor !== 0 )? e.graphic.attr.position.floor:'无',
              "时间": e.graphic.attr.time}
          })
        }
      })
      this.baseHeight = options.layers[6].baseHeight?options.layers[6].baseHeight:0
      this.loadBuildings()
      map.addLayer(this.graphicLayer)
    },
    //场景初始化
    initScene(locations){
      for(let i in locations){
        if(locations[i].status){
          this.allData[locations[i].thing.id] = locations[i]
          this.addThing(locations[i])
        }
      }
      this.calcDepCount()
    },
    //更新定位
    location(location){
      if(this.allData[location.thing.id]){//已存在定位数据
        switch (location.status){
          case "0"://移除并离线
            this.removeThing(location)
            this.updateDepCount(location)
            delete this.allData[location.thing.id]
            break;
          case "1"://移动位置
            this.allData[location.thing.id] = location
            this.moveThing(location)
            break;
          case "2"://设置静止
            this.allData[location.thing.id] = location
            this.silentThing(location)
            break;
          default:
        }
      }else{
        switch (location.status){
          case "0"://忽略
            break;
          case "1"://加入到地图
            this.allData[location.thing.id] = location
            this.addThing(location)
            this.updateDepCount(location)
            break;
          case "2"://加入并设置静止
            this.allData[location.thing.id] = location
            this.silentThing(location)
            this.updateDepCount(location)
            break;
          default:
        }
      }
    },
    //计算统计信息
    calcDepCount(){
      for(let i in this.allData){
        switch (this.allData[i].thing.type.key){
          case 'LOCATION_OBJTYPE:EMP':
            if(this.allData[i].thing.dep){
              this.addDepInfo(this.allData[i].thing.dep.name)
            }else{
              this.addDepInfo("未知部门")
            }
            break;
          case 'LOCATION_OBJTYPE:OUTER':
            this.addDepInfo(this.allData[i].thing.type.value)
            break;
          case 'LOCATION_OBJTYPE:CAR':
            this.addDepInfo(this.allData[i].thing.type.value)
            break;
        }
      }
      this.refreshCountChart()
    },
    //更新统计信息
    updateDepCount(location){
      if(location.status === '0'){
        switch (location.thing.type.key){
          case 'LOCATION_OBJTYPE:EMP':
            if(location.thing.dep){
              this.subDepInfo(location.thing.dep.name)
            }else{
              this.subDepInfo("未知部门")
            }
            break;
          case 'LOCATION_OBJTYPE:OUTER':
            this.subDepInfo(location.type.value)
            break;
          case 'LOCATION_OBJTYPE:CAR':
            this.subDepInfo(location.type.value)
            break;
        }
      }else{
        switch (location.thing.type.key){
          case 'LOCATION_OBJTYPE:EMP':
            if(location.thing.dep){
              this.addDepInfo(location.thing.dep.name)
            }else{
              this.addDepInfo("未知部门")
            }
            break;
          case 'LOCATION_OBJTYPE:OUTER':
            this.addDepInfo(location.type.value)
            break;
          case 'LOCATION_OBJTYPE:CAR':
            this.addDepInfo(location.type.value)
            break;
        }
      }
      this.refreshCountChart()
    },
    //添加定位物体
    addThing(location){
      let url = '';
      switch (location.thing.type.key){
        case 'LOCATION_OBJTYPE:CAR':
          url = "//data.mars3d.cn/gltf/mars/car/aodi1.gltf"
          break;
        default:
          url = "//data.mars3d.cn/gltf/mars/man/walk.gltf"
      }
      const thing = new mars3d.graphic.ModelPrimitive({
        name: location.thing.id,
        position: new mars3d.LatLngPoint(location.position.lng, location.position.lat, this.baseHeight + (location.position.height?location.position.height:0) ),
        style: {
          url: url,
          scale: 1,
          highlight: {
            type: mars3d.EventType.click,
            silhouette: true,
            silhouetteColor: "#FFF",
            silhouetteSize: 2
          },
          label: {
            text: location.thing.name,
            scale: 0.8,
            fontsize: 12,
            color: "#FFFFFF",
            outline: true,
            outlineColor: "#000000",
            outlineWidth: 5,
            pixelOffsetY: -20,
            distanceDisplayCondition_far: 1000,
            distanceDisplayCondition_near: 0,
            visibleDepth: false,
            distanceDisplayCondition: true,
          },
        },
        attr: location,
      })
      this.graphicLayer.addGraphic(thing)
    },
    //移动物体
    moveThing(location){
      const thing = this.graphicLayer.getGraphicByAttr("name", location.thing.id)
      if(thing.attr.position.lng === location.position.lng && thing.attr.position.lat === location.position.lat){

      }else{
        thing.addDynamicPosition(new mars3d.LatLngPoint(location.position.lng, location.position.lat, this.baseHeight + (location.position.height?location.position.height:0) ), 2)
        thing.attr = location
      }
    },
    //移除物体
    removeThing(location){
      const thing = this.graphicLayer.getGraphicByAttr("name", location.thing.id)
      this.graphicLayer.removeGraphic(thing)
    },
    //静止物体
    silentThing(location){
      //thing.attr = location
    },
    //加载建筑
    loadBuildings(){
      let params = {
        "queryParams[pageNum]": 1,
        "queryParams[pageSize]": 99999999
      };
      buildingAreaListAPI(params).then(res => {
        this.buildingData = res.data.content
      });
      let tileLayer = this.map.getLayers("layers", "true")[0]
      let clip = new mars3d.thing.TilesetClip({
        layer: tileLayer
      });
      this.map.addThing(clip)
      this.tilesetClip = clip
    },
    //显示建筑
    showBuilding(building, display){
      if(!building.area || building.area.length === 0){
        return
      }
      if(display){
        this.buildingShowList[building.id] = building
        if(!this.tilesetClipList[building.id]){
          let tempEdge = [];
          for(let i in building.area){
            tempEdge.push(new mars3d.LatLngPoint(building.area[i]._lng, building.area[i]._lat, building.area[i]._alt))
          }
          let tileLayer = this.map.getLayers("layers", "true")[0]
          this.tilesetClipList[building.id] = new mars3d.thing.TilesetPlanClip({
            layer: tileLayer,
            positions: tempEdge,
            clipOutSide: false,
            showPlace: true
          })
          if(building.modelRes.url){
            this.graphicLayer.loadGeoJSON(JSON.parse(building.modelConfig))
          }
        }
        this.map.addThing(this.tilesetClipList[building.id])
        this.tilesetClipList[building.id].enable = true
      }else{
        this.tilesetClipList[building.id].enable = false
        delete this.buildingShowList[building.id]
      }
    },
    //创建或加统计信息
    addDepInfo(key){
      if(this.allDepInfo[key]){
        this.allDepInfo[key] += 1
      }else{
        this.allDepInfo[key] = 1
      }
    },
    //减或删除统计信息
    subDepInfo(key){
      this.allDepInfo[key] -= 1
      if(this.allDepInfo[key] <= 0){
        delete this.allDepInfo[key]
      }
    },
    //刷新统计信息图
    refreshCountChart(){
      let tempData = []
      for(let i in this.allDepInfo){
        tempData.push({name: i, value:this.allDepInfo[i]})
      }
      const chart = this.$refs.chart
      if(chart){
        const myChart = this.$echarts.init(chart)
        const option = {
          tooltip: {
            trigger: 'item',
          },
          legend: {
            bottom: '0',
            left: 'center'
          },
          series: [
            {
              name: '定位统计',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '40',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: tempData
            }
          ]
        }
        myChart.setOption(option)
        window.addEventListener("resize", ()=>{
          myChart.resize()
        })
      }
    },
  }

};
</script>

<style scoped lang='scss'>

</style>
